import React from 'react';
import {Button, Col, DatePicker, Icon, Input, Modal, Row, Select, Table} from 'antd';
import reqwest from 'reqwest';
import moment from 'moment';
import AddForm from './AddForm.js';
import UpdateForm from './UpdateForm.js';

const { Option } = Select;
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD';

class ItemTable extends React.Component {
  state = {
    selectedRowKeys: [], // Check here to configure the default column
    data: [],
    pagination: {
      defaultPageSize: 5,
    },
    sortedInfo: null,
    loading: false,
    visible: false,
    visibleDelete: false,
    visibleUpdate: false,
    confirmLoading: false,

    deleteId: null,
    roleData: {
      itemCode: "物料编码",
      itemDescription: "物料描述",
      itemUom: "物料单位",
      startActiveDate: moment("2019-01-01").format(dateFormat),
      endActiveDate: moment("2019-12-01").format(dateFormat),
      enabledFlag: 1,
      objectVersion:0,
    },

    code: null,
    description: null,
    uom: null,
    startDate: null,
    endDate: null,
    flag: null,
    objectVersion: 0,
  };

  componentDidMount() {
    this.fetch();
  }

  columns = [
    {
      title: '物料编码',
      dataIndex: 'itemCode',
      sorter: true,
      width: '15%',
    },
    {
      title: '物料描述',
      dataIndex: 'itemDescription',
      width: '15%',
    },
    {
      title: '物料单位',
      dataIndex: 'itemUom',
      sorter: true,
      width: '12%',
    },
    {
      title: '生效时间从',
      dataIndex: 'startActiveDate',
      sorter: true,
      width: '14%',
    },
    {
      title: '生效时间至',
      dataIndex: 'endActiveDate',
      sorter: true,
      width: '14%',
    },
    {
      title: '是否启用',
      dataIndex: 'enabledFlag',
      render(enabledFlag){
        return enabledFlag===1?'是':'否'
      },
      sorter: true,
      width: '15%',
    },
    {
      title: '操作',
      key: 'action',
      render: (text,record) => (
          <Button.Group size={"middle"}>
          {/* eslint-disable-next-line no-script-url,jsx-a11y/anchor-is-valid */}
            <Button type="default" onClick={this.showUpdateModal.bind(this,record)}>修改</Button>
            {/* eslint-disable-next-line no-script-url,jsx-a11y/anchor-is-valid */}
            <Button type="danger" onClick={this.showDeleteModal.bind(this,record)}>删除</Button>
      </Button.Group>
      ),
      width: '15%',
    },
    {
      dataIndex: 'itemId',
      render: (text,record) => (
          <span/>
      ),
      width: '1%',
    },
    {
      dataIndex: 'objectVersionNumber',
      render: (text,record) => (
          <span/>
      ),
      width: '1%',
    },
  ];

  handleDeleteOk = () =>{
    console.log(this.state.deleteId );
    this.setState({
      ModalText: 'The modal will be closed after two seconds',
      confirmLoading: true,
    });
    reqwest({
      url: 'http://localhost:8088/materials/delete',
      method: 'DELETE',
      data: {
        itemId: this.state.deleteId,
      },
      type: 'json',
    }).then(data => {
    });
    setTimeout(() => {
      this.setState({
        visibleDelete: false,
        confirmLoading: false,
      });
    }, 1000);
    this.fetch();
};


  handleTableChange = (pagination, filter, sorter) => {
    const pager = { ...this.state.pagination };
    pager.current = pagination.current;
    this.setState({
      pagination: pager,
    });
    this.fetch({
      rows: pagination.pageSize,
      page: pagination.current,
      sortField: sorter.field,
      sortOrder: sorter.order,
      ...filter,
    });
  };

  fetch = (params = {}) => {
    // console.log('params:', params);
    this.setState({ loading: true });
    reqwest({
      url: 'http://localhost:8088/materials/selectItem',
      method: 'GET',
      data: {
        sortField: params.sortField,
        sortOrder: params.sortOrder,
        ...params,
      },
      type: 'json',
    }).then(data => {
      if (data.code !== 0){
        alert(data.message)
      }
      const pagination = { ...this.state.pagination };
      // Read total count from server
      pagination.total = data.data.total;
      this.setState({
        loading: false,
        data: data.data.list,
        pagination,
      });
    });
  };

  start = () => {
    this.setState({
      loading: true,
      pagination:{current:1}
    });
    // ajax request after empty completing
    let ids = this.state.selectedRowKeys;
    console.log(ids.toString());
    reqwest({
      url: 'http://localhost:8088/materials/deleteInBatch',
      method: 'DELETE',
      data: {
        itemIds: ids.toString(),
      },
      // contentType: "application/json",
      // type: 'json',
    }).then(data => {
      if (data.code !== 0){
        alert(data.message)
      }
    });
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading: false,
      });
      this.fetch();
    }, 500);
  };

  onSelectChange = selectedRowKeys => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    this.setState({ selectedRowKeys });
  };

  handleGetCode = (event) => {
    this.setState({
      code : event.target.value,
    })
  };
  handleGetDescription = (event) => {
    this.setState({
      description : event.target.value,
    })
  };
  onUomChange = (value,option) => {
    this.setState({
      uom: value,
    })
  };
  onRangeChange = (date,dateString) => {
    this.setState({
      startDate: dateString[0],
      endDate: dateString[1],
    });
  };
  onFlagChange = (value,option) => {
    this.setState({
      flag : value,
    });
  };

  //新建
  showModal = () => {
    this.setState({ visible: true });
  };

  //删除
  showDeleteModal = (record) => {
    this.setState({
      visibleDelete: true,
      deleteId: record.itemId,
    });
  };
  //更新
  showUpdateModal = (record) => {
  this.setState({
    visibleUpdate: true,
    roleData: record,
    });
  };

  handleCancel = () => {
    this.setState({ visible: false });
  };

  handleDeleteCancel = () => {
    this.setState({
      visibleDelete: false,
    });
  };

  handleUpdateCancel = () => {
    this.setState({
      visibleUpdate: false,
    });
  };

  handleCreate = () => {
    const { form } = this.formRef.props;
    const startDate = this.formRef.getStartDate();
    const endDate = this.formRef.getEndDate();
    form.validateFields((err, values) => {
      if (err) {
        return;
      }
      let flag = values.enabledFlag;
      if(flag === "否"){
        flag = 0;
      }
      if(flag === "是"){
        flag = 1;
      }
      reqwest({
        url: 'http://localhost:8088/materials/add',
        method: 'POST',
        data: {
          itemDescription: values.itemDescription,
          itemUom: values.itemUom,
          startActiveDate: startDate,
          endActiveDate: endDate,
          enabledFlag: flag,
        },
        type: 'json',
      }).then(data => {
        if (data.code !== 0){
          alert(data.message)
        }
        const pagination = { ...this.state.pagination };
        // Read total count from server
        pagination.total = data.data.total;
        this.setState({
          loading: false,
          data: data.data.list,
          ...pagination,
        });
      });
      setTimeout(() => {
      }, 2000);
      this.fetch();
      form.resetFields();
      this.setState({ visible: false });
    });
  };

  handleUpdate = () => {
    this.setState({
      loading:true,
      pagination: {current:1},
    });
    const { form } = this.updateFormRef.props;
    const startDate = this.updateFormRef.getStartDate();
    const endDate = this.updateFormRef.getEndDate();
    form.validateFields((err, values) => {
      if (err) {
        return;
      }
      let flag = values.enabledFlag;
      if(flag === "否"){
        flag = 0;
      }
      if(flag === "是"){
        flag = 1;
      }
      reqwest({
        url: 'http://localhost:8088/materials/update',
        method: 'POST',
        data: {
          itemId: this.state.roleData.itemId,
          itemDescription: values.itemDescription,
          itemUom: values.itemUom,
          startActiveDate: startDate,
          endActiveDate: endDate,
          enabledFlag: flag,
          objectVersionNumber: values.objectVersionNumber,
        },
        type: 'json',
      }).then(data => {
        if (data.code !== 0){
          alert(data.message)
        }
        const pagination = { ...this.state.pagination };
        // Read total count from server
        pagination.total = data.data.total;
        this.setState({
          loading: false,
          data: data.data.list,
          ...pagination,
        });
      });

      form.resetFields();
      this.setState({ visibleUpdate: false });
    });
    this.searchItem();
  };

  saveFormRef = formRef => {
    this.formRef = formRef;
  };

  saveUpdateFormRef = updateFormRef => {
    this.updateFormRef = updateFormRef;
  };

  searchItem = () =>{
    console.log("查询");
    this.setState({
      loading:true,
      pagination: {current:1},
    });
    reqwest({
      url: 'http://localhost:8088/materials/selectItem',
      method: 'GET',
      data: {
        itemCode: this.state.code,
        itemDescription: this.state.description,
        itemUom: this.state.uom,
        startActiveDate: this.state.startDate,
        endActiveDate: this.state.endDate,
        enabledFlag: this.state.flag,
        sortField: this.state.sortField,
        sortOrder: this.state.sortOrder
      },
      type: 'json',
    }).then(data => {
      if (data.code !== 0){
        alert(data.message)
      }
      const pagination = { ...this.state.pagination };
      // Read total count from server
      pagination.total = data.data.total;
      this.setState({
        loading: false,
        data: data.data.list,
        pagination,
      });
    });
  };

  resetSearch = () => {
    this.setState({
      loading: true,
      pagination: {current:1},
      itemCode: null,
      itemDescription: null,
      itemUom: null,
      startActiveDate: null,
      endActiveDate: null,
      sortField: null,
      sortOrder: null
    });
    reqwest({
      url: 'http://localhost:8088/materials/selectItem',
      method: 'GET',
      data: {
      },
      type: 'json',
    }).then(data => {
      if (data.code !== 0){
        alert(data.message)
      }
      const pagination = { ...this.state.pagination };
      // Read total count from server
      pagination.total = data.data.total;
      this.setState({
        loading: false,
        data: data.data.list,
        pagination,
      });
    });
  };

  exportExcel = () =>{
    console.log("excel");
    const aElement = document.createElement('a');
    document.body.appendChild(aElement);
    aElement.style.display = 'none';
    aElement.href = 'http://localhost:8088/materials/getByDateToExcel';
    aElement.click();
    document.body.removeChild(aElement);
  };

  render() {
    const { loading, selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const hasSelected = selectedRowKeys.length > 0;
    return (
        <div style={{margin: 30}}>
          <Input.Group size="large">
            <Row>
              <Col span={5}>
                <Input addonBefore="物料编码" placeholder={"物料编码"} value={this.state.code} onChange={this.handleGetCode}/>
              </Col>
              <Col offset={1} span={5}>
                <Input addonBefore="物料描述" placeholder={"物料描述"} value={this.state.description} onChange={this.handleGetDescription}/>
              </Col>
              <Col offset={1} span={4}>
                <span className="ant-input-wrapper ant-input-group">
                    <span className="ant-input-group-addon">物料单位</span>
                    <Select value={this.state.uom==null?"":this.state.uom} onChange={this.onUomChange}>
                        <Option value="">请选择</Option>
                        <Option value="米">米</Option>
                        <Option value="平方米">平方米</Option>
                        <Option value="立方米">立方米</Option>
                        <Option value="千克">千克</Option>
                        <Option value="个">个</Option>
                        <Option value="其他">其他</Option>
                    </Select>
                </span>
              </Col>
              <Col offset={2} span={1}>
                <Button type="default" style={{height: 40}} onClick={this.searchItem}>
                  <Icon type="search"/>查询
                </Button>
              </Col>
              <Col offset={1} span={1}>
                <Button type="primary" style={{height: 40}} onClick={this.resetSearch}>
                  <Icon type="sync"/>重置
                </Button>
              </Col>
            </Row>
            <br/>
            <Row>
              <Col span={11}>
                <span className="ant-input-wrapper ant-input-group">
                    <span className="ant-input-group-addon">生效周期</span>
                    <RangePicker
                        value={
                          (this.state.startDate==null)||(this.state.endDate==null)?
                              [null,null]:
                              [moment(this.state.startDate),moment(this.state.endDate)]}
                        onChange={this.onRangeChange}
                        format={dateFormat} style={{height: 35}}/>
                </span>
              </Col>
              <Col offset={1} span={4}>
                <span className="ant-input-wrapper ant-input-group">
                    <span className="ant-input-group-addon">是否启用</span>
                    <Select value={this.state.flag==null?"":this.state.flag} onChange={this.onFlagChange}>
                        <Option value="">请选择</Option>
                        <Option value='1'>是</Option>
                        <Option value='0'>否</Option>
                    </Select>
                </span>
              </Col>
              <Col offset={2} span={1}>
                <Button type="default" style={{height: 40}} onClick={this.showModal}>
                  <Icon type="plus"/>新建
                </Button>
                <AddForm
                    wrappedComponentRef={this.saveFormRef}
                    visible={this.state.visible}
                    onCancel={this.handleCancel}
                    onCreate={this.handleCreate}
                />
              </Col>
              <Col offset={1} span={1}>
                <Button type="primary" style={{height: 40}} onClick={this.exportExcel}>
                  <Icon type="download"/>导出
                </Button>
              </Col>
            </Row>
          </Input.Group>
          <br/>
          <div>
            <div style={{ marginBottom: 1 }}>
              <Button type="danger" onClick={this.start} disabled={!hasSelected} loading={loading}>
                批量删除
              </Button>
              <span style={{ marginLeft: 8 }}>
                {hasSelected ? `Selected ${selectedRowKeys.length} items` : ''}
              </span>
            </div>
          </div>
          <Table
              columns={this.columns}
              rowKey={record => record.itemId}
              rowSelection={rowSelection}
              bordered
              dataSource={this.state.data}
              pagination={this.state.pagination}
              loading={this.state.loading}
              onChange={this.handleTableChange}
          />
          <Modal
              title="确认删除"
              visible={this.state.visibleDelete}
              onOk={this.handleDeleteOk}
              confirmLoading={this.state.confirmLoading}
              onCancel={this.handleDeleteCancel}
          >
            <p>确认删除</p>
          </Modal>
          <UpdateForm
              initValues={this.state.roleData}
              wrappedComponentRef={this.saveUpdateFormRef}
              visible={this.state.visibleUpdate}
              onCancel={this.handleUpdateCancel}
              onCreate={this.handleUpdate}
          />

        </div>
    );
  }
}

export default ItemTable;